//替换的配件id
let replaceId = [];
(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };
    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                initSelect(opts);
            });

        }
    });
    //初始化插件
    let productInfo = [];
    function initSelect(o){
        $(document).click(function(){
            var thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                var str = '<div class="input-text">'+
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                let ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_'+ids,
                    id: 'productcodeselecttableid_'+ids,
                    data: productInfo,
                    url:'product/getSpecPartsInfoByConcat',
                    cols: [[
                        {field: 'productCode', width: 120, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_'+ids+')', function(obj){
                    let data = obj.data;
                    //字段重新映射
                    data["id"] = null;
                    data["fjCode"] = data["specificationCode"];
                    data["chinaname"] = data["productCname"];
                    data["englishname"] = data["productEname"];
                    data["cpbl"] = 1;
                    data["pjbl"] = 1;
                    data["mz"] = data["grossWeight"];
                    data["jz"] = data["netWeight"];
                    data["tj"] = data["bulk"];
                    let tableData = table.cache["productsatableid"];
                    $.each(tableData,function(index,value){
                        if(value.tempId == ids){
                            data.tempId = ids;
                            if(!isEmpty(value.id)){
                                replaceId.push(value.id);
                            }
                            tableData[index] = data;
                        }
                    });
                    table.reload('productsatableid', {data: tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode == 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value,name){
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        let tableData = table.cache["productsatableid"];
        $.each(tableData, function(index, values){
            if(values.tempId == ids){
                tableData[index]["productCode"] = value;
                //$(".value_"+values.tempId).html(value);
            }
        });
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_'+ids,{where: {
                info:value
            }});
    }
})(window.jQuery);
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,upload = layui.upload
    ,userphotos="",
    form = layui.form,$ = layui.jquery,id=getQueryVariable("id"),isUsed = getQueryVariable("isUsed"),
img_count=0,file_count=0,maincode="",imgs=[],wjs=[];
let selectdata=[];

var tpdata = [{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明"
},{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明"
},{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明"
}];
var fjdata = [{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明",
    "name":"文件名"
},{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明",
    "name":"文件名"
},{
    "url":"statics/images/layui-logo.jpg",
    "shuom":"说明",
    "name":"文件名"
}];

var dw=getdictionary(3,10);//单位
var cgbz=getdictionary(5,14);//采购币种
var gys=getgys();//供应商集合
var fjCode="";//附件规格型号
var cataCodeName=JSON.parse(window.sessionStorage.getItem("cataCodeName"));//没用
var  cataCode=JSON.parse(window.sessionStorage.getItem("cataCode"));//被修改产品的目录编码
let cataCodeMo=window.sessionStorage.getItem('cataCodeMo');//主页 左边树被点击目录的编码
var code="";
if(id !=""){
    code=JSON.parse(window.sessionStorage.getItem("code"));//产品编码
}
var hs=getdictionary(3,8);//海关

$("input[name='vatRate']").attr("readOnly",true);
$("input[name='taxreRates']").attr("readOnly",true);
$("input[name='importTariff']").attr("readOnly",true);

var hsselect=$("select[name='hgCode']");//客户等级
hsselect.append(getoptionHs(hs));

//新增:true 修改:false
let addFlag = true;
if(!isEmpty(id)){
    //修改
    addFlag = false;
    if(!isEmpty(isUsed)){
        $('#editor-form').find('input,textarea,select').attr('disabled',true);
        document.getElementById("imgId").style.display = "none";
        document.getElementById("annexId").style.display = "none";
        form.render();
    }
}
//获取目录结构
queryPid();
//目录树
let productTreeList=[];
//产品目录
let treeList=toTree(selectdata);
if(treeList){
    let productTree = getAllJson(treeList);
    productTreeList=getxmselect("#directory","cataCode", productTree)
}else {
    productTreeList=getxmselect("#directory","cataCode", [])
}

form.on("select(hgCodeFilter)", function(data){
    var hg=data.value;
    for(var i=0;i<hs.length;i++){
        if(hg==hs[i].code){
            $("input[name='vatRate']")[0].value=hs[i].vatRate;
            $("input[name='taxRate']")[0].value=hs[i].taxRate;
            $("input[name='importTariff']")[0].value=hs[i].importTariff;
            break;
        }else{
            $("input[name='vatRate']")[0].value="";
            $("input[name='taxRate']")[0].value="";
            $("input[name='importTariff']")[0].value="";
        }
    }
    form.render();
});


//监听上级目录下拉框
form.on("select(upDirectoryFilter)", function(data){
    $("#directory").empty();
    let code=data.value;
    getDirectory(code);
})


function getUpDirectory() {
    queryPid();
    $("#upDirectory").append("<option value=''></option>");
    for (var i = 0; i < selectdata.length; i++) {
        $("#upDirectory").append("<option value=\"" + selectdata[i].code +  "\">" + selectdata[i].name + "</option>");
    }
}
//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}
function getDirectory(code) {
    let upDirectoryTemp;

        for (let i in selectdata) {
            if (code==selectdata[i].code){
                upDirectoryTemp=selectdata[i];
            }
        }
    if (!isEmpty(upDirectoryTemp)){
        let pidArr=[]
        for (var i = 0; i < selectdata.length; i++) {
            if (upDirectoryTemp.id==selectdata[i].pid){
                pidArr.push(selectdata[i]);
            }
        }
        if (pidArr.length<=0){
            pidArr.push(upDirectoryTemp);
        }
        for (let i in pidArr) {
            $("#directory").append("<option value=\"" + pidArr[i].code +  "\">" + pidArr[i].name + "</option>");
        }

        form.render();
    }
}


//表单初始值，修改时调用
if(id!=""){
    $("input[name='code']").attr("readOnly",true);
    var obj=init(id);//回显
    // getUpDirectory();
    // let upCataCodePath=obj.upCataCode;
    // let upCataCode="";
    // if (!isEmpty(upCataCodePath)){
    //     for (let i in selectdata) {
    //         if (upCataCodePath==selectdata[i].path){
    //             upCataCode=selectdata[i].code;
    //             break;
    //         }
    //     }
    // }
    // getDirectory(upCataCode);
    cataCode=obj.cataCode;
    form.val("editor-form",{
        "code":obj.code,
        "chinaName":obj.chinaName,
        "englishName":obj.englishName,
        "hgCode":obj.hgCode,
        "customerCode":obj.customerCode,
        "remark":obj.remark
    });
    // $("#upDirectory").val(upCataCode);
    // $("#directory").val(obj.cataCode);
    productTreeList.setValue([ cataCode ]);

    var hgname="";
    var hg=obj.hgCode;
    for(var i=0;i<hs.length;i++){
        if(hg==hs[i].code){
            hgname=hs[i].name;
            $("input[name='vatRate']")[0].value=hs[i].vatRate;
            $("input[name='taxRate']")[0].value=hs[i].taxRate;
            $("input[name='importTariff']")[0].value=hs[i].importTariff;
            break;
        }else{
            $("input[name='vatRate']")[0].value="";
            $("input[name='taxRate']")[0].value="";
            $("input[name='importTariff']")[0].value="";
        }
    }

    tpdata=JSON.parse(obj.img);

    for(var i = 0;i<tpdata.length;i++){
        img_count ++;
        var newImg ='<div class="img_tj">'+
            '<div class="img_wdiv"><img src="'+tpdata[i]+'" id="imgUpload_'+img_count+'"></div>'+
            '<div class="de_div">'+
            /*'<input name="img_instructions'+img_count+'" class="layui-input" placeholder="图片说明" value="'+tpdata[i].shuom+'">'+*/
            '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;" id="imgUpload_sc_'+img_count+'"></i>'+
            '</div>'+
            '</div>';
        $('#addimgdiv').append(newImg);
        imgs.push(tpdata[i]);
        uploadImgRender("#imgUpload_"+img_count,"#imgUpload_sc_"+img_count);
    }
    fjdata=JSON.parse(obj.wj);
    for(var i = 0;i<fjdata.length;i++){
        file_count ++;
        var filename=fjdata[i].split("filename=")[1];
        var filenames=fjdata[i].split("pathname=")[1].split("&filename=");
        var pathA=filenames[0];//"c:/a/a/"
        var fnas=filenames[1].split("&originalFileName=");
        filename=fnas[1];
        pathA=pathA+"/"+fnas[0];
        var newFile ='<div class="img_tj">'+
            '<div class="file_wdiv"><a style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="'+filename+'" id="file_span'+file_count+'" download="'+filename+
            '" href="javascript:void(0);" onclick="onLineFile(\''+pathA+'\');">'+filename+'</a>' +
            '<a type="button" class="layui-btn" id="fileUpload_'+file_count+'"><i class="layui-icon"></i>上传附件</a></div>'+
            '<div class="de_div">'+
            '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;margin-right:20px;" ' +
            'id="fileUpload_sc_'+file_count+'"></i>'+
            '<i class="layui-icon layui-icon-download-circle" style="font-size: 30px; color: #000000;line-height: 30px;" onclick="downFileLoadNew(\''+filename+'\',\''+pathA+'\');"></i>'+
            '</div>'+
            '</div>';
        $('#addfilediv').append(newFile);
        wjs.push(fjdata[i]);
        uploadFileRender("#fileUpload_"+file_count,"#fileUpload_sc_"+file_count,"#file_span"+file_count);
    }

    form.render();
}else{
    form.val("editor-form",{
        "code":"",
        "chinaName":"",
        "englishName":"",
        "hgCode":"",

        "customerCode":"",

        "remark":""
    });
    $("input[name='vatRate']")[0].value="";
    $("input[name='taxRate']")[0].value="";
    $("input[name='importTariff']")[0].value="";
    $('#addimgdiv').html("");
    $('#addfilediv').html("");

    // for (let i = 0; i < selectdata.length; i++) {
    //     if (cataCodeMo==selectdata[i].code){
    //         $("#directory").val(selectdata[i].code);
    //     }
    // }
    productTreeList.setValue([cataCode]);
    form.render();
}

function init(id){
    var obj=[];
    $.ajax({
        type : 'get',
        data:{"id":id},
        url:'productmaininfo/queryById',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
               obj=da.data;

            }
        }
    });
    return obj;
}
//---规格查询
table.render({
    elem: '#productselect'
    ,type:"get"
    ,url:"productfjinfo/selectByPage"
    ,where:{
        "code":code
    }
    ,toolbar: '#producttoolbar'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field: 'code', title: '规格编码',event:'specificationcoding', width: 120, sort: true}
        ,{field:'categoryName', title:'种类', width: 120, sort: true}
        ,{field:'categoryCode', title:'种类编码', hide: true,  width: 120, sort: true}
        ,{field:'moldCategoryName', title:'模具类别', width: 120, sort: true}
        ,{field:'moldCategoryCode', title:'模具类别编码', hide: true,  width: 120, sort: true}
        ,{field:'firstCategoryName', title:'品类', width: 120, sort: true}
        ,{field:'firstCategoryCode', title:'品类编码', hide: true,  width: 120, sort: true}
        ,{field:'secondaryCategoryName', title:'规格', width: 120, sort: true}
        ,{field:'secondaryCategoryCode', title:'规格编码', hide: true,  width: 120, sort: true}
        ,{field:'threeCategoryName', title:'材质', width: 120, sort: true}
        ,{field:'threeCategoryCode', title:'材质编码', hide: true,  width: 120, sort: true}
        ,{field:'craftName', title:'工艺', width: 120, sort: true}
        ,{field:'craftCode', title:'工艺编码', hide: true,  width: 120, sort: true}
        ,{field:'colorOrderNumberName', title:'颜色订货号', width: 120, sort: true}
        ,{field:'colorOrderNumberCode', title:'颜色订货号编码', hide: true,  width: 120, sort: true}
        ,{field:'privateMoldNumberName', title:'私模订货号', width: 120, sort: true}
        ,{field:'privateMoldNumberCode', title:'私模订货号编码', hide: true,  width: 120, sort: true}
        ,{field:'specialNeedsName', title:'特殊需求(配件)', width: 120, sort: true}
        ,{field:'specialNeedsCode', title:'特殊需求(配件)编码', hide: true,  width: 120, sort: true}
        ,{field: 'ge', title: '规格说明', width: 120, sort: true}
        ,{field:'chinaRemark', title:'中文描述', width: 120, sort: true}
        ,{field:'englishRemark', title:'英文描述', width: 120, sort: true}
        ,{field:'bzsm', title:'每托箱数', width: 120, sort: true}
        ,{field:'cpjz', title:'净重KGS/CTN', width: 120, sort: true}
        ,{field:'cpmz', title:'毛重KGS/CTN', width: 120, sort: true}
        ,{field: 'colour', title: '颜色', width: 120, sort: true}
        ,{field:'dw', title:'单位', width: 120, sort: true}
        ,{field:'cgbz', title:'采购币种', width: 120, sort: true}
        ,{field:'cgcb', title:'含税出厂价', width: 120, sort: true}
        ,{field:'cgcbws', title:'未税出厂价', width: 120, sort: true}
        ,{field:'fob', title:'含税FOB价', width: 120, sort: true}
        ,{field:'cshh', title:'未税FOB价', width: 120, sort: true}
        ,{field:'wbzc', title:'外包装长mm', width: 120, sort: true}
        ,{field:'wbzk', title:'外包装宽mm', width: 120, sort: true}
        ,{field:'wbzg', title:'外包装高mm', width: 120, sort: true}
        // ,{field:'wbzcc', title:'外包装尺寸', width: 120, sort: true}
        ,{field:'wbzsl', title:'每箱数量', width: 120, sort: true}
        ,{field:'tj', title:'体积', width: 120, sort: true}
        // ,{field:'gys', title:'供应商', width: 120, sort: true}
        ,{field:'hq40zl', title:'40HQ装量', width: 120, sort: true}
        ,{field:'gp20', title:'20GP', width: 120, sort: true}
        ,{field:'gp40', title:'40GP', width: 120, sort: true}
        ,{field:'lclpx', title:'LCL拼箱', width: 120, sort: true}
        ,{fixed: 'right', width:150, align:'center', toolbar: '#productup', title:'操作'}
    ]]
    ,id: 'producttableid'
    ,page: true
    ,height:300
    ,done:function(res, curr, count){

        $("[data-field = 'cgbz']").children().each(function(){
            /*if($(this).text() == '1'){
                $(this).text("共享");
            }*/
            for(var i=0;i<cgbz.length;i++){
                if($(this).text()==cgbz[i].code){
                    $(this).text(cgbz[i].name);
                }
            }
        })
        $("[data-field = 'dw']").children().each(function(){
            /*if($(this).text() == '1'){
                $(this).text("共享");
            }*/
            for(var i=0;i<dw.length;i++){
                if($(this).text()==dw[i].code){
                    $(this).text(dw[i].name);
                }
            }
        })
        $("[data-field = 'gys']").children().each(function(){
            /*if($(this).text() == '1'){
                $(this).text("共享");
            }*/
            for(var i=0;i<gys.length;i++){
                if($(this).text()==gys[i].code){
                    $(this).text(gys[i].name);
                }
            }
        })



    }
});
//规格型号新增、删除
table.on('toolbar(producttable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'new':
            if(id =="" ){
                layer.msg("请先保存产品主信息");
                return false;
            }
            // layer.msg("添加");
            layer.open({
                type: 2,
                area: ['1488px', '800px'],
                content: 'views/jsp/BasicData/tpl/newupproductspecification.jsp'
            });
            break;
        case 'delet':
            let data = checkStatus.data, delList = [];
            data.forEach(function (n, i) {
                delList.push(n.id);
            });
            if(delList!=''){
                layer.confirm('确定删除所选项吗？',function (index) {
                    if(delfjinfo(delList)){
                        layer.msg('删除成功');
                        layer.close(index);
                        refrash();
                    }else{
                        layer.msg('删除失败');
                    }

                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});
//行内修改、删除
table.on('tool(producttable)', function(obj) {
    var data = obj.data;
    fjCode=data.code;
    if (obj.event === 'productup') {
        layer.open({
            type: 2,
            area: ['1488px', '800px'],
            content: 'views/jsp/BasicData/tpl/newupproductspecification.jsp?id=' + obj.data.id+'&oldCode='+obj.data.code
        });
        // layer.msg('修改');
    } else if (obj.event === 'productde') {
        layer.confirm('真的删除行么', function (index) {
            var delList = [];
            delList.push(data.id);
            if (delfjinfo(delList)) {
                layer.msg('删除成功');
                layer.close(index);
                refrash();
            } else {
                layer.msg('删除失败');
            }
        });
    } else if (obj.event === 'specificationcoding') {
        $("#hidden").show();
        //获取配件数据
        let specData = getSpecData(data);
        table.render({
            elem: '#productsaselect'
            , data: specData
            , toolbar: '#productsatoolbar'
            , cols: [[
                {checkbox: true, fixed: true}
                , {field: 'productCode', title: '产品编码', templet:'#productcodeselect',style:"color:#009688"}
                , {field: 'fjCode', title: '规格编码', sort: true}
                , {field: 'cpbl', title: '成品比例', edit: 'text'}
                , {field: 'pjbl', title: '配件比例', edit: 'text'}
                , {field: 'chinaname', title: '中文名称', sort: true}
                , {field: 'englishname', title: '英文名称', sort: true}
                , {field: 'mz', title: '毛重', sort: true}
                , {field: 'jz', title: '净重', sort: true}
                , {field: 'tj', title: '体积', sort: true}
                , {fixed: 'right', width: 150, align: 'center', toolbar: '#productsaup', title: '操作'}
            ]]
            , id: 'productsatableid'
            , page: true
            , height: 400
            ,done: function (res, curr, count) {
                $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
                $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
                for (var i = 0; i < res.data.length; i++) {
                    let tempId = res.data[i].tempId;
                    let classs = ".y_" + tempId;
                    $(classs).ySearchSelect(classs);
                }
            }
        });

        table.render({
            elem: '#asupplierselect'
            , type: "get"
            , url: "productfjgysbak/selectByPage"
            , toolbar: '#asuppliertoolbar'
            , where: {
                "productCode": code,
                "fjCode": data.code
            } //查询的产品ID，条件
            , cols: [[
                {checkbox: true, fixed: true}
                , {field: 'code', title: '供应商', sort: true}
                , {field: 'fob', title: '含税FOB价', sort: true}
                , {field: 'cshh', title: '未税FOB价', sort: true}
                , {field: 'cgbz', title: '采购币种', sort: true}
                , {field: 'cgcb', title: '含税出厂价', sort: true}
                , {field: 'catalog', title: '未税出厂价', sort: true}
                , {field: 'createDate', title: '创建日期', sort: true}
                , {field: 'updateDate', title: '修改日期', sort: true}
                , {fixed: 'right', width: 150, align: 'center', toolbar: '#asupplierup', title: '操作'}
            ]]
            , id: 'asuppliertableid'
            , page: true
            , height: 300
            , done: function (res, curr, count) {

                $("[data-field = 'cgbz']").children().each(function () {

                    for (var i = 0; i < cgbz.length; i++) {
                        if ($(this).text() == cgbz[i].code) {
                            $(this).text(cgbz[i].name);
                        }
                    }
                })

                $("[data-field = 'code']").children().each(function () {
                    /*if($(this).text() == '1'){
                        $(this).text("共享");
                    }*/
                    for (var i = 0; i < gys.length; i++) {
                        if ($(this).text() == gys[i].code) {
                            $(this).text(gys[i].name);
                        }
                    }
                })

                $("[data-field = 'catalog']").children().each(function () {
                    if ($(this).text() == cataCode) {
                        $(this).text(cataCodeName);
                    }
                })

            }


        });

        table.render({
            elem: '#boxGaugeSelect'
            ,data:[]
            , url: "boxGauge/findBoxGaugeListByPage"
            , toolbar: '#boxGaugeToolbar'
            , where: {
                "productCode": code,
                "specificationCode": fjCode,
            }
            , cols: [[
                {checkbox: true, fixed: true}
                , {field: 'productCode', title: '产品编码', hide:true}
                , {field: 'specificationCode', title: '规格编码', hide:true}
                , {field: 'containerCode', title: '货柜型号',hide:true}
                , {field: 'containerName', title: '货柜型号', sort: true}
                , {field: 'boxNum', title: '箱数', sort: true}
                , {field: 'boxGrossWeight', title: '单箱毛重', sort: true}
                , {field: 'boxNetWeight', title: '单箱净重', sort: true}
                , {field: 'boxNumPallet', title: '纸箱数量/托数', sort: true}
                , {field: 'numPallet', title: '数量/托数', sort: true}
                , {field: 'createDate', title: '创建日期', sort: true}
                , {field: 'updateDate', title: '修改日期', sort: true}
                , {fixed: 'right', width: 150, align: 'center', toolbar: '#boxGaugeSet', title: '操作'}
            ]]
            , id: 'boxGaugeTableId'
            , page: true
            , height: 300
        });

        table.render({
            elem: '#priceRangeSelect'
            ,data:[]
            , url: "priceRange/findPriceRangeListByPage"
            , toolbar: '#priceRangeToolbar'
            , where: {
                "productCode": code,
                "specificationCode": fjCode,
            }
            , cols: [[
                {checkbox: true, fixed: true}
                , {field: 'productCode', title: '产品编码', hide:true}
                , {field: 'specificationCode', title: '规格编码', hide:true}
                , {field: 'supplyName', title: '供应商名称'}
                , {field: 'supplyCode', title: '供应商编码'}
                , {field: 'minNum', title: '最小起订量 ', sort: true}
                , {field: 'maxNum', title: '最大起订量', sort: true}
                , {field: 'taxIncludedFactory', title: '含税出厂价', sort: true}
                , {field: 'unTaxIncludedFactory', title: '未税出厂价', sort: true}
                , {field: 'taxIncludedFob', title: '含税FOB价', sort: true}
                , {field: 'unTaxIncludedFob', title: '未税FOB价', sort: true}
                , {field: 'createDate', title: '创建日期', sort: true}
                , {field: 'updateDate', title: '修改日期', sort: true}
                , {fixed: 'right', width: 150, align: 'center', toolbar: '#priceRangeSet', title: '操作'}
            ]]
            , id: 'priceRangeTableId'
            , page: true
            , height: 300
        });

    }
});

//监听配件表修改
table.on('edit(productsatable)', function (obj) {
    //旧值
    let old = $(this).prev().text();
    //判断数据类型
    if ((obj.field == "cpbl" ||
        obj.field == "pjbl") && !isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
});

//获取配件数据
function getSpecData(data) {
    let specData = [];
    $.ajax({
        url: "productfjge/selectProductFjGe?zhuge=" + data.code + "&mainProductCode=" + data.productCode,
        async: false,
        success: function (res) {
            if (res.status == 200) {
                specData = res.data;
            }
        }
    });
    //添加临时id
    for(let i in specData){
        let tempId = GenNonDuplicateID(3) + (i + 1);
        specData[i]["tempId"] = tempId;
    }
    return specData;
}

//产品配件新增、删除
table.on('toolbar(productsatable)', function(obj){
    let checkStatus = table.checkStatus(obj.config.id);
    let data = checkStatus.data;
    switch(obj.event){
        case 'new':
            let oldData = table.cache["productsatableid"];
            let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
            let newData = {
                "tempId": tempId,
                "productCode": "",
                "fjCode" : "",
                "cpbl" : 1,
                "pjbl" : 1,
                "chinaname" : "",
                "englishname" : "",
                "mz" : 0,
                "jz" : 0,
                "tj" : 0
            };
            oldData.push(newData);
            table.reload('productsatableid', {data: oldData});
            break;
        case 'delet':
            let delList = [];
            data.forEach(function (n, i) {
                delList.push(n.tempId);
            });
            if (delList != '') {
                layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                    let cbList = table.cache["productsatableid"];
                    for (var i = 0; i < cbList.length; i++) {
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                if(!isEmpty(cbList[i].id)){
                                    //获取要删除原有的配件id
                                    replaceId.push(cbList[i].id);
                                }
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("productsatableid", {data: cbList});
                    layer.msg('删除成功');
                })
            } else {
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});
table.on('tool(productsatable)', function(obj){
    let data = obj.data;
    if(obj.event === 'productsaup') {
        layer.open({
            type: 2,
            area: ['908px', '500px'],
            content: 'views/jsp/BasicData/tpl/newupproductsa.jsp?id='+obj.data.id
        });
        // layer.msg('修改');
    }else if(obj.event === 'productsade') {
        let oldData =  table.cache["productsatableid"];
        layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
            for(let i in oldData){
                if(oldData[i].tempId == data.tempId){
                    if(!isEmpty(data.id)){
                        //获取要删除原有的配件id
                        replaceId.push(data.id);
                    }
                    oldData.splice(i, 1);
                    table.reload('productsatableid',{data : oldData});
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
        });
    }
    return false;
});
//新增中的新增产品附件、备选 供应商
table.on('toolbar(asuppliertable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch(obj.event){
        case 'new':       //规格型号新增
            // layer.msg("添加");
            layer.open({
                type: 2,
                area: ['908px', '380px'],
                content: 'views/jsp/BasicData/tpl/newupasupplier.jsp'
            });
            break;
        case 'delet'://规格型号删除
            var delid = [];
            for (var i = 0;i<data.length;i++){
                delid.push(data[i].id)
            }
            if(delid.length ==0){
                layer.msg("请选择要删除的数据");
                break;
            }
            if(delgys(delid)){
                layer.msg("删除成功");
                refrash_gys();
            }else{
                layer.msg("删除失败");
            }
            /*layer.msg('需要删除的数据ID为：'+ JSON.stringify(delid) + ',执行删除');
            table.reload('asuppliertableid',{}); //ajax删除成功之后刷新表格*/
            break;
    };
    return false;
});
table.on('tool(asuppliertable)', function(obj){
    var data = obj.data;
    if(obj.event === 'asupplierup') {
        layer.open({
            type: 2,
            area: ['908px', '380px'],
            content: 'views/jsp/BasicData/tpl/newupasupplier.jsp?id='+obj.data.id
        });
        // layer.msg('修改');
    }else if(obj.event === 'asupplierde') {
        layer.confirm('真的删除行么', function (index) {
            var delid = [];
            delid.push(data.id);
            if(delgys(delid)){
                layer.msg("删除成功");
               //refrash_gexh();
                obj.del();
            }else{
                layer.msg("删除失败");
            }

            layer.close(index);
        });
    }
});
//添加，删除 产品箱规
table.on('toolbar(boxGaugeTable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch(obj.event){
        case 'new':
            layer.open({
                type: 2,
                area: ['908px', '500px'],
                content: 'views/jsp/BasicData/tpl/newUpBoxGauge.jsp'
            });
            break;
        case 'delet':
            var ids = [];
            for (var i = 0;i<data.length;i++){
                ids.push(data[i].id)
            }
            if(ids.length==0){
                layer.msg("请选择要删除的数据");
                break;
            }
            delBox(ids);
            break;
    };
    return false;
});
//修改，删除 产品箱规
table.on('tool(boxGaugeTable)', function(obj){
    var data = obj.data;
    if(obj.event === 'boxGaugeUp') {
        layer.open({
            type: 2,
            area: ['908px', '500px'],
            content: 'views/jsp/BasicData/tpl/newUpBoxGauge.jsp?id='+obj.data.id
        });
    }else if(obj.event === 'boxGaugeDel') {
        layer.confirm('真的删除行么', function (index) {
            var ids = [];
            ids.push(data.id);
            delBox(ids);
            layer.close(index);
        });
    }
    return false;
});

//添加，删除 区间价格
table.on('toolbar(priceRangeTable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch(obj.event){
        case 'new':
            layer.open({
                type: 2,
                area: ['908px', '500px'],
                content: 'views/jsp/BasicData/tpl/newUpPriceRange.jsp'
            });
            break;
        case 'delet':
            var ids = [];
            for (var i = 0;i<data.length;i++){
                ids.push(data[i].id)
            }
            if(ids.length==0){
                layer.msg("请选择要删除的数据");
                break;
            }
            delPrice(ids);
            break;
    };
    return false;
});
//修改，删除 区间价格
table.on('tool(priceRangeTable)', function(obj){
    var data = obj.data;
    if(obj.event === 'priceRangeUp') {
        layer.open({
            type: 2,
            area: ['908px', '500px'],
            content: 'views/jsp/BasicData/tpl/newUpPriceRange.jsp?id='+obj.data.id
        });
    }else if(obj.event === 'priceRangeDel') {
        layer.confirm('真的删除行么', function (index) {
            var ids = [];
            ids.push(data.id);
            delPrice(ids);
            layer.close(index);
        });
    }
    return false;
});



//---日志
table.render({
    elem: '#infoselect'
    //,data:data1
    ,type:"get"
    ,url:"productlog/selectByPage"
    ,where:{
        "code":code
    }
    ,cols: [[
        {field:'type', title:'操作类型', sort: true}
        ,{field:'optioner', title:'操作员名称', sort: true}
        ,{field:'time', title:'更新日期',  sort: true}
        ,{field:'content', title:'操作内容', sort: true}
    ]]
    ,id: 'infoselecttableid'
    ,page: true
    ,height:350
});

//监听提交---保存
form.on('submit(form-save)', function(data){
    //产品类型(1:包材不可选配件 2:配件 3:包材可选配件 4:其它)
    data.field["productType"] = 3;
    //主信息保存
    let parentDataSaveFlag = savemain(data.field);
    //配件信息保存
    let specPartsDataSaveFlag = true;
    //获取配件数据
    let specPartsData = table.cache["productsatableid"];
    if(!isEmpty(specPartsData) && specPartsData.length > 0){
        specPartsDataSaveFlag = saveSpecParts(specPartsData);
    }
    //删除配件信息
    let specPartsDataDelFlag = true;
    if(replaceId.length > 0){
        specPartsDataDelFlag = delgexh(replaceId);
        if(specPartsDataDelFlag){
            //删除成功,清空数据id
            replaceId = [];
        }
    }
    if(parentDataSaveFlag && specPartsDataSaveFlag && specPartsDataDelFlag){
        layer.msg('保存成功');
    }else{
        layer.msg('保存失败');
    }
   // layer.msg('保存');
    //layui.table.cache[表格ID] 表格数据获取方式
   /* setTimeout(function () {
        //保存成功则刷新提交过来的界面 并关闭此页面
        parent.detab("views/jsp/BasicData/product.jsp");
        parent.intab("views/jsp/BasicData/product.jsp","产品")
        parent.detab("views/jsp/BasicData/tpl/newupproduct.jsp"+(id==''?'':'?id='+id));
    },1000)*/
    return false;
});

//配件新增、修改
function saveSpecParts(dataInfo) {
    let saveFlag = false;
    for(let i in dataInfo){
        dataInfo[i]["zhuge"] = fjCode;
        dataInfo[i]["mainProductCode"] = code;
        $.ajax({
            type: 'post',
            data: JSON.stringify(dataInfo[i]),
            url: 'productfjge/savege',
            dataType: "json",
            contentType: 'application/json',
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    saveFlag = da.data > 0;
                }
            }
        });
        if(!saveFlag){
            break;
        }
    }
    return saveFlag;
}
//可用于修改动态生成 图片
$("#newimg").on('click',function () {
    img_count ++;
    var newImg ='<div class="img_tj">'+
                    '<div class="img_wdiv"><img src="statics/images/layui-logo.jpg" id="imgUpload_'+img_count+'"></div>'+
                    '<div class="de_div">'+
                       /* '<input name="img_instructions'+img_count+'" class="layui-input" placeholder="图片说明">'+*/
                        '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;" id="imgUpload_sc_'+img_count+'"></i>'+
                    '</div>'+
                '</div>';
    $('#addimgdiv').append(newImg);
    uploadImgRender("#imgUpload_"+img_count,"#imgUpload_sc_"+img_count);
});

function uploadImgRender(e,uploadimd) {
    var uploadImg = upload.render({
        elem: e
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"productimg"}//头像
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                console.log(uploadImg);
                $(e).attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.status !=200) {
                return layer.msg('上传失败');
            }
            //上传成功

               /* var img_sb = img_wdiv.find('.img_sb');
                if(img_sb.length != 0){
                    img_sb.remove();
                }*/

                var ftpPath=res.data[0].ftpPath;
                var fileName=res.data[0].fileName;
                var src=getFtpPath(ftpPath,fileName);
                imgs.push(src);
                return layer.msg('上传成功');


           /* //如果上传失败
            if(res.status !=200){
                return layer.msg('上传失败');
            }else{
                var ftpPath=res.data[0].ftpPath;
                var fileName=res.data[0].fileName;
                var src=getFtpPath(ftpPath,fileName);
                $("#userphotos").attr('src',src);
                $("input[name='logo']")[0].value=src;
            }*/
            //上传成功
        }
        , error: function () {
            //演示失败状态，并实现重传
            var img_wdiv = $(e).parent();
            var img_sb = img_wdiv.find('.img_sb');
            if(img_sb.length == 0){
                img_wdiv.append('<div class="img_sb"><a class="layui-btn layui-btn-xs demo-reload">重试</a></div>');
                img_wdiv.find('.demo-reload').on('click', function () {
                    uploadImg.upload();
                });
            }
        }
    });

    $(uploadimd).on('click',function () {
        let pathD=$(e).attr("src")
        for (let i = 0; i <imgs.length ; i++) {
            if (imgs[i]==pathD){
                imgs.splice(i,1);
            }
        }
        $(uploadimd).parent().parent().remove();
    })
}

function uploadImgRender22(e,uploadimd) {
    var uploadImg = upload.render({
        elem: e
        , url: 'https://httpbin.org/post' //改成您自己的上传接口
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                console.log(uploadImg);
                $(e).attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.error > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
            if (res.error == 0) {
                var img_sb = img_wdiv.find('.img_sb');
                if(img_sb.length != 0){
                    img_sb.remove();
                }
                return layer.msg('上传成功');
            }
        }
        , error: function () {
            //演示失败状态，并实现重传
            var img_wdiv = $(e).parent();
            var img_sb = img_wdiv.find('.img_sb');
            if(img_sb.length == 0){
                img_wdiv.append('<div class="img_sb"><a class="layui-btn layui-btn-xs demo-reload">重试</a></div>');
                img_wdiv.find('.demo-reload').on('click', function () {
                    uploadImg.upload();
                });
            }
        }
    });

    $(uploadimd).on('click',function () {
        $(uploadimd).parent().parent().remove();
    })
}
//文件
$("#newfile").on('click',function () {
    file_count ++;
    var newFile ='<div class="img_tj">'+
      '<div class="file_wdiv"><div style="height: 25px;"><a style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="file_span'+file_count+'" id="file_span'+file_count+'" '+
        '   onclick="getPathOnLine(this);"></a>&nbsp;</div>' +
       // '<a style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="file_span'+file_count+'" id="file_span'+file_count+'"></a>' +
        '<a type="button" class="layui-btn" id="fileUpload_'+file_count+'">  ' +
        ' <i class="layui-icon"></i>上传附件</a></div>'+
      '<div class="de_div">'+
      '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;margin-right:20px;"  id="fileUpload_sc_'+file_count+'"></i>'+

        '<i class="layui-icon layui-icon-download-circle" style="font-size: 30px; color: #000000;line-height: 30px;display: none;"   id="fileDownload_sc_'+file_count+'" ></i>'+
      '</div>'+
      '</div>';

    $('#addfilediv').append(newFile);
    uploadFileRender("#fileUpload_"+file_count,"#fileUpload_sc_"+file_count,"#file_span"+file_count,"#fileDownload_sc_"+file_count);
});
function getPathOnLine(path){
  //  alert(path);
    //onLineFile
    var name=path.text;
    var pathA="";
    for(var i=0;i<wjs.length;i++){
        var ph=wjs[i];
        if(ph.indexOf(path.text)!=-1){
            var filename=ph.split("filename=")[1];
            var filenames=ph.split("pathname=")[1].split("&filename=");
            var pathA=filenames[0];//"c:/a/a/"
            var fnas=filenames[1].split("&originalFileName=");
            filename=fnas[1];
            pathA=pathA+"/"+fnas[0];
            onLineFile(pathA);
           // return false;
        }
    }
   /* var filename=fjdata[i].split("filename=")[1];
    var filenames=fjdata[i].split("pathname=")[1].split("&filename=");
    var pathA=filenames[0];//"c:/a/a/"
    var fnas=filenames[1].split("&originalFileName=");
    filename=fnas[1];
    pathA=pathA+"/"+fnas[0];*/

}
function uploadFileRender(e,uploadimd,name,download) {
    var uploadfile = upload.render({
        elem: e
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"productwj"}//头像
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $(name).html(file.name);
               // $(name).attr("href",result);
               // $(name).attr("download",file.name);
                $(name).attr("title",file.name);
                $(download).css("display","block");
            });
        }
        , done: function (res) {


            //如果上传失败
            if (res.status !=200) {
                return layer.msg('上传失败');
            }
                var ftpPath=res.data[0].ftpPath;
                var fileName=res.data[0].fileName;
                var originalFileName=res.data[0].originalFileName;
                fileName=fileName+"&originalFileName="+originalFileName;
                var src=getFtpPath(ftpPath,fileName);
                wjs.push(src);

                return layer.msg('上传成功');

        }
        , error: function () {
            //演示失败状态，并实现重传
            var file_wdiv = $(e).parent();
            var img_sb = file_wdiv.find('.img_sb');
            if(img_sb.length == 0){
                file_wdiv.append('<div class="img_sb"><a class="layui-btn layui-btn-xs demo-reload">重试</a></div>');
                file_wdiv.find('.demo-reload').on('click', function () {
                    uploadfile.upload();
                });
            }
        }
    });


//移除
    $(uploadimd).on('click',function () {
        ///let pathD=$(name).attr("href")
        let pathD=$(name)[0].innerText;
        for (let i = 0; i <wjs.length ; i++) {
            if (wjs[i].indexOf(pathD)){//wjs[i]==pathD){
                wjs.splice(i,1);
            }
        }
        $(uploadimd).parent().parent().remove();
    })
    //下载
    $(download).on('click',function () {
        downFileload2($(name)[0].href,$(name)[0].text);
    })
}
function savemain(data) {
    if(id !="") data.id=id;
    maincode=data.code;
    data.cataCode=productTreeList.getValue('valueStr');//所属目录
    for (let i in selectdata) {
        if (data.cataCode==selectdata[i].code){
            data.upCataCode=selectdata[i].path;//上级目录
            break;
        }
    }
    window.sessionStorage.setItem("code",maincode);
    code=window.sessionStorage.getItem("code");
    data.img=JSON.stringify(imgs);
    data.wj=JSON.stringify(wjs);
    var tf=false;
    $.ajax({
        type : 'post',
        data:JSON.stringify(data),
        url:'productmaininfo/savemain',
        dataType:"json",
         contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf= da.data >0 ;
                id=da.data;//
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
//关闭
$("#shutdown").on('click',function () {
    // parent.detab("views/jsp/BasicData/tpl/customerinfo.jsp"+(id==''?'':'?id='+id));
    setTimeout(function () {
        //保存成功则刷新提交过来的界面 并关闭此页面
        parent.detab("views/jsp/BasicData/product.jsp");
        parent.intab("views/jsp/BasicData/product.jsp","产品")
        parent.detab("views/jsp/BasicData/tpl/newupproduct.jsp"+(id==''?'':'?id='+id),"修改产品");
    },1000)
})
/*function  getoption(objs) {
    var stoptions="<option value=''></option>";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"</option>";
    }
    return stoptions;
}*/
//图片、文件上传
function upload() {
    upload.render({
        elem: '#logoadd'
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"customerlogo"}//头像
        ,before: function(obj) {
            /*var thin = this;
            obj.preview(function(index, file, result){
                $("#"+thin.id+"").attr('src', result); //图片链接（base64）
            });*/

        }
        ,done: function(res){
            //如果上传失败
            if(res.status !=200){
                return layer.msg('上传失败');
            }else{
                var ftpPath=res.data[0].ftpPath;
                var fileName=res.data[0].fileName;
                var src=getFtpPath(ftpPath,fileName);
                $("#userphotos").attr('src',src);
                $("input[name='logo']")[0].value=src;
            }
            //上传成功
        }
        ,error: function(){
            layer.msg('上传失败,请稍后重试')
        }
    })
}
function delfjinfo(ids) {
    var tf=false;
    $.ajax({
        type : 'post',
        data:{"ids":JSON.stringify(ids)},
        url:'productfjinfo/delfjinfo',
        dataType:"json",
        /* contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf= da.data >0 ;

            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function refrash() {
    table.reload('producttableid', {
        type:"get"
        ,url:"productfjinfo/selectByPage"
        ,where:{
            "code":code
        },
        page: {
            curr: 1 //重新从第 1 页开始
        }

    }, 'data');
}
//获取所有供应商
function  getgys() {
    var gys=[];
    $.ajax({
        type : 'get',
        url:'customer2/getAllGys',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                //gys=da.data;
                for(var i=0;i<da.data.length;i++){
                    var obj={};
                    obj.code=da.data[i].code;
                    obj.name=da.data[i].name;
                    gys.push(obj);
                }

            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return gys;
}
function  getoption(objs) {
    var stoptions="<option value=''></option>";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"</option>";
    }
    return stoptions;
}
function  getoptionHs(objs) {
    var stoptions="<option value=''></option>";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"["+objs[i].code+"]</option>";
    }
    return stoptions;
}
//批量删除规格型号
function delgexh(ids) {
    let tf = false;
    $.ajax({
        type: 'post',
        data: {"ids": JSON.stringify(ids)},
        url: 'productfjge/delgexh',
        dataType: "json",
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data > 0;
            }
        },
        error: function (data) {
        }
    });
    return tf;
}
//批量删除备选供应商
function delgys(ids) {
    var tf=false;
    $.ajax({
        type : 'post',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'productfjgysbak/delgys',
        dataType:"json",
        /* contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf= da.data >0 ;

            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

//批量删除区间价格
function  delPrice(ids) {
    $.ajax({
        url:'priceRange/delPrice?ids='+ids,
        async:false,
        success : function (da) {
            if(da.status==200 ){
                layer.msg("删除成功");
                refresh_price();
            }else {
                layer.msg("删除失败");
            }
        },
    });
}
//批量删除产品箱规
function  delBox(ids) {
    $.ajax({
        url:'boxGauge/delBox?ids='+ids,
        async:false,
        success : function (da) {
            if(da.status==200 ){
                layer.msg("删除成功");
                refresh_box();
            }else {
                layer.msg("删除失败");
            }
        },
    });
}

function  refrash_gexh() {
    table.reload('productsatableid',{
         type: "get"
        , url: "productfjge/selectByPage"

        , where: {
            // "productCode": code,
            "zhuge": fjCode
         }
        ,
        page: {
            curr: 1 //重新从第 1 页开始
        }
    },'data');
}
function refrash_gys() {
    table.reload('asuppliertableid',{
        type: "get"
        , url: "productfjgysbak/selectByPage"
        , where: {
            "productCode": code,
            "fjCode":  fjCode
        }
        ,
        page: {
            curr: 1 //重新从第 1 页开始
        }
    }, 'data');
/*, type: "get"
        , url: "productfjge/selectByPage"
        , toolbar: '#productsatoolbar'
        , where: {
        "productCode": code,
            "fjCode": data.code
    } //查询的产品ID，条件*/
}
/**
 * 刷新区间价格
 */
function  refresh_price() {
    table.reload('priceRangeTableId',{
        type: "get"
        , url: "priceRange/findPriceRangeListByPage"
        , where: {
            "productCode": code,
            "specificationCode": fjCode
        },
        page: {
            curr: 1 //重新从第 1 页开始
        }
    },'data');
}
/**
 * 刷新产品箱规
 */
function  refresh_box() {
    table.reload('boxGaugeTableId',{
        type: "get"
        , url: "boxGauge/findBoxGaugeListByPage"
        , where: {
            "productCode": code,
            "specificationCode": fjCode
        },
        page: {
            curr: 1 //重新从第 1 页开始
        }
    },'data');
}

function  isExisCode(obj) {
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data:{"code":$("input[name='code']")[0].value},
        url:'productmaininfo/isexit',
        dataType:"json",
        /* contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
               if(da.data){
                   layer.msg("编码重复，重新输入");
                   $("input[name='code']")[0].value="";
                    $("#code").focus();
               }

            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
}

//获取目录结构
function queryPid() {
    $.ajax({
        type : 'get',
        url:'productcatalog/getProductDirectoryInfo',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                selectdata=da.data;
            }
        }
    });
}

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

function getIsContainsRoleProduct(){
    $.ajax({
        url: 'productmaininfo/isContainsRoleProduct',
        async: false, // 同步
        success: function (data) {
            if (data.status==200){
                isContainsRoleProduct=data.data;
            }
        }
    });
}


function isNumber(val) {
    let regPos = /^\d+(\.\d+)?$/; //非负浮点数
    let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["children"]){
            tmparr["children"]=  getAllJson(item["children"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }
    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        autoRow: true,
        filterable: true,
        radio: true,
        tree: {
            show: true,
            showFolderIcon: true,
            showLine: true,
            indent: 20,
            expandedKeys: [ -3 ],
            strict: false,
        },
        height: '300px',
        data: data,
        on: function(data){
            if(data.isAdd){
                return data.change.slice(0, 1)
            }
        },
    });
}
//json转tree
function toTree(data) {
    let result = []
    if(!Array.isArray(data)) {
        return result
    }
    let map = {};
    data.forEach(item => {
        map[item.id] = item;
    });
    data.forEach(item => {
        let parent = map[item.pid];
        if(parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            result.push(item);
        }
    });
    return result;
}
